package main

import (
	"fmt"
	"net"
)

const (
	IPv4len = 4
	IPv6len = 16
)

func parseIPv4(ipstr string) net.IP {
	if ip := net.ParseIP(ipstr);ip !=nil {
		return ip.To4()
	}
	return nil
}
func parseIPv6(ipstr string) net.IP {
	if ip := net.ParseIP(ipstr);ip !=nil && ip.To4() == nil  {
		return ip
	}
	return nil
}

func SnatMemberCheck(start, end string, prefixlength uint8, isv4 bool) (bool, net.IP, net.IP) {
	if prefixlength == 0 {
		fmt.Println("有无效的掩码长度,掩码长度不能为0")
		return false,nil,nil
	}
	ip1 := net.ParseIP(start)
	ip2 := net.ParseIP(end)
	if ip1 == nil || ip2 == nil {
		fmt.Println("有无效的IP地址格式")
		return false,nil,nil
	}
	ip41 := ip1.To4()
	ip42 := ip2.To4()
	if isv4 {
		if ip41 == nil || ip42 == nil {
			fmt.Println("有无效的IPv4地址")
			return false,nil,nil
		}
		if prefixlength > 32 {
			fmt.Println("有无效的IPv4掩码")
		}
		mask := net.CIDRMask(int(prefixlength), 32)
		if !ip41.Mask(mask).Equal(ip42.Mask(mask)) {
			return false,nil,nil
		}

	} else {
		if ip41 != nil || ip42 != nil {
			fmt.Println("有无效的IPv6地址")
			return false,nil,nil
		}
		if prefixlength > 128 {
			fmt.Println("有无效的IPv4掩码")
			return false,nil,nil
		}
		mask := net.CIDRMask(int(prefixlength), 128)
		if !ip1.Mask(mask).Equal(ip2.Mask(mask)) {
			return false,nil,nil
		}
	}
	return !IPCompare(ip1, ip2),ip1,ip2
}

//  IPCompare Compare ip1 and ip2
//  return true if ip1 > ip2 else false
func IPCompare(ip1, ip2 net.IP) bool {
	if len(ip1) != len(ip2) {
		return false
	}
	for i := range ip1 {
		if ip1[i] > ip2[i] {
			return true
		}
	}
	return false
}

type SnatPool struct {
	Name       string
	Gatetway   string
	RoundRobin bool
	Vrid       int
	IsV4       bool
	Members    []*SnatPoolMember
}

func (p *SnatPool) Check() bool {
	total := len(p.Members)
	for i:=0;i<total;i++ {
		 ret,ip1,ip2:=SnatMemberCheck(p.Members[i].Start,p.Members[i].End,p.Members[i].PrefixLength,p.IsV4)
		 if !ret {
			 return false
		 }
		 for j:=1;j<total;j++ {
			 if
		 }
	}
}

type SnatPoolMember struct {
	Start        string
	End          string
	PrefixLength uint8
	Gateway      string
}

func SnatPoolCheck()

func main() {
	fmt.Println(SnatMemberCheck("192.168.1.1", "192.168.2.1", 24))
	fmt.Println(SnatMemberCheck("192.168.1.1", "192.168.1.255", 24))

}
